package com.chennan.websocket.api.controller;


import com.chennan.websocket.domain.model.RequestMessage;
import com.chennan.websocket.domain.model.ResponseMessage;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;

import java.security.Principal;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chennan
 * @create 2021-08
 */
@Api(tags = "websocket前端")
@Controller
public class BroadcastCtl {

    private AtomicInteger count = new AtomicInteger();

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * @MessageMapping 指定要接收消息的地址，类似@RequestMapping。除了注解到方法上，也可以注解到类上
     * @SendTo默认 消息将被发送到与传入消息相同的目的地
     * 消息的返回值是通过{@link org.springframework.messaging.converter.MessageConverter}进行转换
     * @param content
     * @return
     */
    @MessageMapping("/receive")
//    @SendTo("/topic/getResponse")
    public void broadcast(RequestMessage msg){
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setResponseMessage("BroadcastCtl receive [" + count.incrementAndGet() + "] records");
        messagingTemplate.convertAndSendToUser(msg.getName(), "/queue/getResponse",msg.getMsg());
//        return responseMessage;
    }

}
